import { Component, OnInit } from '@angular/core';
import {Maintenance} from "../../shared/model/maintenance";
import {MaintenanceService} from "../../shared/service/maintenance.service";
import {Router} from "@angular/router";

@Component({
  selector: 'app-maintenance-list',
  templateUrl: './maintenance-list.component.html',
  styleUrls: ['./maintenance-list.component.css']
})
export class MaintenanceListComponent implements OnInit {
  types: Maintenance[];
  oldTypes: Maintenance[];
  selectedType: Maintenance;
  constructor(private maintenanceService:MaintenanceService,private router:Router) { }

  ngOnInit() {
    this.getMaintenanceTypes();

    this.maintenanceService.searchEvent.subscribe(
      param => {
        let result = this.oldTypes;
        if (param) {
          result = result.filter((f: Maintenance) => f.name.indexOf(param) !== -1);
        }
        this.types = result;
      }
    );

    this.maintenanceService.listFreshEvent.subscribe(
      param => {
        if (param) {
          this.maintenanceService.searchFreshEvent.emit("reset");
          this.getMaintenanceTypes();
        }
      }
    );
  }

  getMaintenanceTypes(){
    this.maintenanceService.getMaintenanceTypes().then(
      res => {
        this.types = res;
        this.oldTypes = res;
      }
    );
  }

  onSelect(type: Maintenance): void {
    this.selectedType = type;
  }

  delType(type: Maintenance):void {
    if(confirm("确认删除?")){
      this.maintenanceService.deleteMaintenanceType(type.oid).then(
        res => {
          alert(res.message);
          this.maintenanceService.searchFreshEvent.emit("reset");
          this.router.navigateByUrl('/maintenance/new');
          this.getMaintenanceTypes();
        }
      )
    }
  }

}
